/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package DataAccess;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import Entity.InfoDatabase;
import java.sql.DriverManager;
/**
 *
 * @author Toshiba Satellite
 */
public class DBUtil {
    private static Connection con = null;
    private static String fileconfig = "config.properties";
    
    public static InfoDatabase getInfoDB()
    {
        Properties p = new Properties();
        InfoDatabase idb = null;
        File f = new File(fileconfig);
        if(f!=null||f.exists())
        {
            try {
                FileInputStream fis = new FileInputStream(fileconfig);
                p.load(fis);
                idb = new InfoDatabase(
                p.getProperty("Server"),
                p.getProperty("Port"),
                p.getProperty("Databasename"),
                p.getProperty("Username"),
                p.getProperty("Password")
                );
                
            } catch (Exception e) {
                  Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE,null,e);
            }
            
        }
        return idb;

    }
    
    public static void setInfoDB(InfoDatabase idb)
    {
        Properties p = new Properties();
        try {
            FileOutputStream fos = new FileOutputStream(fileconfig);
            p.setProperty("Server", idb.getServer());
            p.setProperty("Port", idb.getPort());
            p.setProperty("Databasename", idb.getDatabase());
            p.setProperty("Username", idb.getUser());
            p.setProperty("Password", idb.getPass());
            p.store(fos, "Marvel Consultancies Ltd - Group 5 - eproject - FPT Greenwich");
            fos.close();
            
        } catch (Exception e) {
            
        }
    }
    
    public static Connection getConnection(InfoDatabase idb)
    {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            
            con = DriverManager.getConnection(
                    "jdbc:sqlserver://"
                    +idb.getServer()+":"
                    +idb.getPort()+";Database="
                    +idb.getDatabase(),idb.getUser(),idb.getPass()
                    );                                   
            
        } catch (Exception e) {
            return null;
        }
        return con;
    }

    public static void close(Connection c)
    {
        try {
            if(c!=null||c.isClosed())
            {
                c.close();
                c= null;
            }

        } catch (Exception e) {
            Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE,null,e);

        }

    }
    
    
}
